package com.sdy.resdir.biz.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.approval.api.ApprovalAllApi;
import com.sdy.approval.biz.model.TpApproveFlow;
import com.sdy.approval.biz.model.TpOrder;
import com.sdy.common.model.BizException;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.mvc.service.impl.BaseServiceImpl;
import com.sdy.resdir.biz.mapper.RdIpUpdateApplicationMapper;
import com.sdy.resdir.biz.model.*;
import com.sdy.resdir.biz.param.IpApplyParam;
import com.sdy.resdir.biz.service.*;
import com.sdy.resdir.biz.vo.IpApplyInfoVo;
import com.sdy.resdir.biz.vo.IpApplyListVo;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.DeptDto;
import com.sdy.usercenter.api.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * ip修改申请 服务实现类
 * </p>
 *
 * @author hyh
 * @since 2019-10-28
 */
@Slf4j
@Service
public class RdIpUpdateApplicationServiceImpl extends BaseServiceImpl<RdIpUpdateApplication> implements RdIpUpdateApplicationService {
    @Resource
    private RdIpUpdateApplicationMapper ipUpdateApplyMapper;
    @Autowired
    private ApprovalAllApi approvalAllApi;
    @Autowired
    private UserQueryApi userQueryApi;
    @Autowired
    private RdIpChangeService ipChangeService;
    @Autowired
    private RdSelfBuiltSystemService appService;
    @Autowired
    private RdResourceDirService resourceDirService;
    @Autowired
    private RdIpImpleOrderService rdIpImpleOrderService;
    @Autowired
    private RdIpUpdateApplicationService rdIpUpdateApplicationService;
    @Value("${res.app.code}")
    private String appCode;
    @Value("${res.dept.code}")
    private String deptCode;
    @Value("${res.approval.authCode}")
    private String authCode;
    @Value("${res.approval.roleCode}")
    private String roleCode;

    @Override
    public IPage<IpApplyListVo> getUserIpOrderList(Page page, String appName, String ip, Integer state, Integer userId) {
        // 如果传入订单状态为 2 ,则转换为3
        if (null != state && state == 2) {
            state = 3;
        }
        UserDTO user = userQueryApi.getUser(userId);
        // 创建参数类
        IpApplyParam ipApplyParam = new IpApplyParam().setUserId(userId).setDeptId(user.getOwnDeptId()).setSize(page.getCurrent() * page.getSize())
                .setCurrent((page.getCurrent() - 1) * page.getSize()).setName(appName).setIp(ip).setState(state);
        List<IpApplyListVo> userIpApplyList = ipUpdateApplyMapper.getUserIpApplyList(ipApplyParam);
        String ipId = userIpApplyList.stream().map(IpApplyListVo::getIpId).collect(Collectors.joining(","));
        List<RdIpChange> list = ipChangeService.list(Wrappers.<RdIpChange>lambdaQuery().in(RdIpChange::getId, Arrays.asList(ipId.split(","))));
        // 对比查询出来的订单列表和ip列表,如果ip的id一致则放入ip信息
        for (IpApplyListVo applyListVo : userIpApplyList) {
            for (RdIpChange ipChange : list) {
                if (!applyListVo.getIpId().isEmpty()&&applyListVo.getIpId().contains(ipChange.getId() + "")) {
                    applyListVo.getIpList().add(ipChange.getNewIp());
                    applyListVo.setIpId(applyListVo.getIpId().replace(ipChange.getId() + "", ""));
                }
            }
        }
        // 在列表中放入订单的部门以及用户信息
        for (IpApplyListVo listVo : userIpApplyList) {
            listVo.setUserName(user.getName()).setUserDept(user.getOwnDeptName());
        }
        int userIpApplyListTotal = ipUpdateApplyMapper.getUserIpApplyListTotal(ipApplyParam.setIpOrderIdList(null));
        IPage<IpApplyListVo> voIPage = new Page<>();
        voIPage.setTotal(userIpApplyListTotal);
        voIPage.setRecords(userIpApplyList);
        voIPage.setSize(page.getSize());
        voIPage.setPages(userIpApplyListTotal + page.getSize() - 1 / page.getSize());
        voIPage.setRecords(userIpApplyList);
        voIPage.setCurrent(page.getCurrent());
        return voIPage;
    }

    @Override
    public IPage<IpApplyListVo> getManagerIpOrderList(Page page, String appName, String ip, Integer state, Integer userId) {
        // 如果传入订单状态为 2 ,则转换为3
        if (null != state && state == 2) {
            state = 3;
        }
        // 创建参数类
        IpApplyParam ipApplyParam = new IpApplyParam().setUserId(null).setDeptId(null).setSize(page.getCurrent() * page.getSize())
                .setCurrent((page.getCurrent() - 1) * page.getSize()).setName(appName).setIp(ip).setState(state);
        IPage<IpApplyListVo> vo = new Page<>();
        UserDTO user = userQueryApi.getUser(userId);
        List<TpOrder> ipApplyList = approvalAllApi.selectTpOrderApprovalByCondition(user.getOwnDeptIdList(), user.getRoleIdList(), null, null, null, "[资源目录]-");
        // 给参数类设置需要查询的订单号列表,该用户的数据从审批中心给出的单号列表中查询
        List<String> orderList = ipApplyList.stream().map(TpOrder::getApplicationNum).collect(Collectors.toList());
        if (orderList.isEmpty()) {
            return vo;
        }
        // 获取查询到的订单列表
        List<IpApplyListVo> userIpApplyList = ipUpdateApplyMapper.getUserIpApplyList(ipApplyParam.setIpOrderIdList(orderList));
        String ipId = userIpApplyList.stream().map(IpApplyListVo::getIpId).collect(Collectors.joining(","));
        List<RdIpChange> list = ipChangeService.list(Wrappers.<RdIpChange>lambdaQuery().in(RdIpChange::getId, Arrays.asList(ipId.split(","))));
        // 对比查询出来的订单列表和ip列表,如果ip的id一致则放入ip信息
        for (IpApplyListVo applyListVo : userIpApplyList) {
            for (RdIpChange ipChange : list) {
                if (applyListVo != null && ipChange != null && applyListVo.getIpId().contains(ipChange.getId() + "")) {
                    applyListVo.getIpList().add(ipChange.getNewIp());
                    applyListVo.setIpId(applyListVo.getIpId().replace(ipChange.getId() + "", ""));
                }
            }
        }
        // 获取订单列表用户id,然后根据用户id查询用户信息列表
        List<Integer> userIdList = userIpApplyList.stream().map(IpApplyListVo::getApplyUserId).collect(Collectors.toList());
        if (!userIdList.isEmpty()) {
            List<UserDTO> userDTOS = userQueryApi.listUser(userIdList);
            for (IpApplyListVo listVo : userIpApplyList) {
                for (UserDTO dto : userDTOS) {
                    if (listVo.getApplyUserId().equals(dto.getId())) {
                        listVo.setUserName(dto.getName());
                        listVo.setUserDept(dto.getOwnDeptName());
                    }
                }
            }
        }
        // 给列表数据设置节点信息
        List<TpApproveFlow> newFlowInfo = approvalAllApi.selectApprovalFlowByNumOrderList(ipApplyParam.getIpOrderIdList(), user.getOwnDeptIdList(), user.getRoleIdList());
        for (TpApproveFlow flow : newFlowInfo) {
            for (IpApplyListVo listVo : userIpApplyList) {
                if (listVo.getApplyNum().equals(flow.getApplyId())) {
                    listVo.setResult(flow.getResult());
                }
            }
        }
        int userIpApplyListTotal = ipUpdateApplyMapper.getUserIpApplyListTotal(ipApplyParam.setUserId(null));
        vo.setTotal(userIpApplyListTotal);
        vo.setSize(page.getSize());
        vo.setCurrent(page.getCurrent());
        vo.setPages(userIpApplyListTotal + page.getSize() - 1 / page.getSize());
        vo.setRecords(userIpApplyList);
        return vo;
    }

    @Override
    public IpApplyInfoVo getIpApplyInfo(Integer userId, Integer applyId) throws BizException {
        IpApplyInfoVo orderVo = new IpApplyInfoVo();
        RdIpUpdateApplication ipApply = ipUpdateApplyMapper.selectById(applyId);
        Assert.isNull(ipApply, "没有找到该订单信息");
        orderVo.setApplyId(ipApply.getId()).setApplyNo(ipApply.getApplyNum());
        // 获取自建系统信息
        RdSelfBuiltSystem appInfo = appService.getOne(Wrappers.<RdSelfBuiltSystem>lambdaQuery().eq(RdSelfBuiltSystem::getId, ipApply.getAppId()));
        orderVo.setAppName(appInfo.getSysName());
        orderVo.setAppCode(appInfo.getSysCode());
        orderVo.setDescription(appInfo.getSysDescribe());
        List<RdIpChange> ipChangeList = ipChangeService.list(Wrappers.<RdIpChange>lambdaQuery().in(RdIpChange::getId, Arrays.asList(ipApply.getIpId().split(","))));
        // 查询到IP修改数据后放入对应的资源名称
        List<String> resIdList = ipChangeList.stream().map(RdIpChange::getNewResIdList).collect(Collectors.toList());
        resIdList.addAll(ipChangeList.stream().map(RdIpChange::getOldResIdList)
                .filter(oldResIdItem -> StringUtil.isNotBlank(oldResIdItem) && StringUtil.isNotEmpty(oldResIdItem))
                .collect(Collectors.toList()));
        String[] resIds = String.join(",", resIdList).split(",");
        // TODO 此处可能造成了重复的resId查询
        List<RdResourceDir> resList = resourceDirService.list(Wrappers.<RdResourceDir>lambdaQuery().in(RdResourceDir::getId, resIds));
        for (RdIpChange ipChange : ipChangeList) {
            for (RdResourceDir resourceDir : resList) {
                if (ipChange.getNewResIdList() != null && ipChange.getNewResIdList().contains(resourceDir.getId() + "")) {
                    ipChange.getNewResName().add(resourceDir.getResName());
                    ipChange.setNewResIdList(ipChange.getNewResIdList().replace(resourceDir.getId() + "", ""));
                }
                if (ipChange.getOldResIdList() != null && ipChange.getOldResIdList().contains(resourceDir.getId() + "")) {
                    ipChange.getOldResName().add(resourceDir.getResName());
                    ipChange.setOldResIdList(ipChange.getOldResIdList().replace(resourceDir.getId() + "", ""));
                }
            }
        }
        orderVo.setIpList(ipChangeList);
        // 获取流程审批模块该订单的节点信息
        List<TpApproveFlow> tpApproveFlows = approvalAllApi.selectApprovalFlowByResId(ipApply.getApplyNum());
        orderVo.setFlowList(tpApproveFlows);
        // 放入最新的节点信息,判断是否需要审核
        if (!tpApproveFlows.isEmpty()) {
            orderVo.setFlowResult(tpApproveFlows.get(tpApproveFlows.size() - 1).getResult());
        } else {
            orderVo.setFlowResult(1);
        }

        // 获取ip实施工单数据
        String applyNum = ipApply.getApplyNum();
        RdIpImpleOrder one = rdIpImpleOrderService.getOne(Wrappers.<RdIpImpleOrder>lambdaQuery().eq(RdIpImpleOrder::getApplyNum, applyNum));
        orderVo.setRdIpImpleOrder(one);
        return orderVo;
    }

    @Override
    public int ipOrderApproval(Integer userId, Integer result, String remark, String ipApplyNo) throws Exception {
        Assert.isTrue(null == result || null == remark || null == ipApplyNo, "提交参数错误");
        Assert.isBlank(ipApplyNo, "单号不可为空");
        RdIpUpdateApplication rdIp = rdIpUpdateApplicationService.getOne(new LambdaQueryWrapper<RdIpUpdateApplication>().eq(RdIpUpdateApplication::getApplyNum, ipApplyNo));
        Assert.isNull(rdIp, "无法获取ip变动列表");
        Assert.isNull(rdIp.getIpId(), "无法获取ip变动列表");
        RdIpChange rdIpChange = ipChangeService.getOne(new LambdaQueryWrapper<RdIpChange>().eq(RdIpChange::getId, rdIp.getIpId()));
        Assert.isNull(rdIpChange, "无法获取ip变动列表");
        UserDTO user = userQueryApi.getUser(userId);
        DeptDto deptBase = userQueryApi.getDeptByCode(deptCode);
        Integer deptBaseId = deptBase.getId();
        int roleBaseId = userQueryApi.getRoleByCode(roleCode).getId();
        if (result == 2 || result == 3) {
            TpApproveFlow tpflow = new TpApproveFlow();
            tpflow.setResult(result);
            //   ApplyId
            tpflow.setApplyId(ipApplyNo);
            tpflow.setUserId(userId);
            tpflow.setResId("[资源目录]-" + rdIpChange.getNewResIdList());
            tpflow.setAuditOpinion(remark);
            approvalAllApi.updateIpNodeApprovalResults(tpflow, user.getOwnDeptIdList(), user.getRoleIdList(), deptBaseId, roleBaseId);
        }
        return 0;
    }
}
